package com.idenger.modules.edu.web.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONObject;
/**
 * Created by zp on 17/6/27.
 */
public class Tools {
    static Logger logger = LoggerFactory.getLogger("Tools");

    // 生成随机指定位数的字符_指定位数的数字【用于注册用户后生成用户的昵称】
    public static String getStringRandom(int charLength, int numLength) {

        String val = "";
        Random random = new Random();

        // 参数length，表示生成几位随机数
        for (int i = 0; i < charLength; i++) {
            // 输出是大写字母还是小写字母
            int temp = 97;// random.nextInt(2) % 2 == 0 ? 65 : 97;
            val += (char) (random.nextInt(26) + temp);
        }
        val += "_";
        for (int i = 0; i < numLength; i++) {
            val += String.valueOf(random.nextInt(10));

        }
        return val;
    }

    public static String getStringAfter(String str, int index, int length) {
        str = str.substring(index, length);
        return str;
    }

    /**
     * 随机生成指定位数的数字
     *
     * @param nums
     * @return
     * @author Trinity
     */
    public static String generateRandom(int nums) {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < nums; i++) {
            result += random.nextInt(10);
        }
        return result;
    }

    // 生成随机数字和字母,
    public static String getStringRandom(int length) {

        String val = "";
        Random random = new Random();

        // 参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

	/** 
	  * 将emoji表情替换成空串 
	  *   
	  * @param source 
	  * @return 过滤后的字符串 
	  */  
	 public static String filterEmoji(String source) {  
	  if (source != null && source.length() > 0) {  
	   return source.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", "");  
	  } else {  
	   return source;  
	  }  
	 }
    /**
     * 将请求传过来的json串解码
     *
     * @param json
     * @return
     * @throws UnsupportedEncodingException
     * @author Trinity
     */
    public static String decoderStr(String json) throws UnsupportedEncodingException {
        String jsonStr = "";
        jsonStr = URLDecoder.decode(json, "UTF8");
        if (jsonStr.substring(jsonStr.length() - 1).equals("=")) {
            jsonStr = jsonStr.substring(0, jsonStr.length() - 1);
        }

        return jsonStr;
    }

    // 获取昨天的日期，返回年-月-日格式字符串
    public static String getYeasday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date d = cal.getTime();

        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
        String ZUOTIAN = sp.format(d);// 获取昨天日期
        return ZUOTIAN;
    }

    // 获取今天的日期，返回年-月-日格式字符串
    public static String getToday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);
        Date d = cal.getTime();

        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
        String ZUOTIAN = sp.format(d);// 获取昨天日期
        return ZUOTIAN;
    }

    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(String str) {
        if (StringUtils.isNotEmpty(str)) {
            Pattern p = null;
            Matcher m = null;
            boolean b = false;
            p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
            m = p.matcher(str);
            b = m.matches();
            return b;
        } else {
            return false;
        }
    }

    public static boolean checkPost(String post) {
        if (post.matches("^[1-9][0-9]{5}$")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEmail(String str) {
        Pattern p = Pattern.compile("^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
        Matcher m = p.matcher(str);
        boolean b = m.matches();
        System.out.print(b);// true
        return b;
    }

    /**
     * 按指定日期，指字格式，返回指定天数后的时间
     *
     * @作者：wangjj @生成时间：2010-12-10 下午02:22:58
     * @param date
     *            指定日期
     * @param day
     *            指定天数
     * @param sdf
     *            日期格式
     * @return
     * @throws ParseException
     *
     *
     */
    public static Date getDateAfter(Date date, int day, String format) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        String dateStr = sdf.format(now.getTime());
        return sdf.parse(dateStr);
    }

    /*
     * money是指币种额度；num是要分成几张； 返回分开后的币种的组合 *
     */
    public static int[] billRandom(int money, int num) {
        int[] bill = { 5, 10, 20, 50, 100 };

        // while (money % num != 0) {
        // num =num-1;
        // if(num==0) num = num+1;
        // }
        int[] result = new int[num];
        for (int i = 0; i < num; i++) {
            result[i] = 0;
        }
        int indx = 0, sumBill = 0;
        while (true) {
            int a = (int) (Math.random() * bill.length);
            if (result[indx] == 0) {
                result[indx] = bill[a];
                sumBill += result[indx];
                indx++;
            }
            if (indx == result.length) {
                if (sumBill == money) {
                    break;
                } else {
                    // 清理重新生成
                    for (int i = 0; i < num; i++) {
                        result[i] = 0;
                    }
                    indx = 0;
                    sumBill = 0;
                }
            }

        }
        return result;
    }

    // public static void main(String[] args) {
    // System.out.println(isMobile("18308765678"));
    // String str =
    // "tokenId=382d0cc7bf7d82b2dc386aa087d4bf0c&%7B%22activity%22%3A%5B%7B%22title%22%3A%22%E6%A0%87%E9%A2%98%22%2C%22content%22%3A%22%E6%B4%BB%E5%8A%A8%E7%AE%80%E4%BB%8B%E5%86%85%E5%AE%B9%22%2C%22posterImg%22%3A%22%E5%9B%BE%E7%89%87%E8%B7%AF%E5%BE%84%22%2C%22beginTime%22%3A%222015-06-25+14%3A00%3A00%22%2C%22endTime%22%3A%222015-18%3A00%3A00%22%7D%5D%7D=";
    // try {
    // str = URLDecoder.decode(str, "UTF-8");
    // } catch (UnsupportedEncodingException e) {
    //
    // e.printStackTrace();
    // }
    // System.out.println("str:"+str);
    // }

    /**
     * 比较两个日期格式的字符串
     *
     * @param DATE1
     *            日期一
     * @param DATE2
     *            日期二
     * @return 比较大小
     * @author Trinity
     */
    public static int compare_dateStr(String DATE1, String DATE2) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            Date dt1 = df.parse(DATE1);
            Date dt2 = df.parse(DATE2);
            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 比较两个日期大小
     *
     * @param dt1
     *            日期一
     * @param dt2
     *            日期二
     * @return 比较大小
     * @author Trinity
     */
    public static int compare_date(Date dt1, Date dt2) {

        try {

            if (dt1.getTime() > dt2.getTime()) {
                System.out.println("dt1 在dt2前");
                return 1;
            } else if (dt1.getTime() < dt2.getTime()) {
                System.out.println("dt1在dt2后");
                return -1;
            } else {
                return 0;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return 0;
    }

    /**
     * 从Json中获取keys[]中的值，保存在Map中，返回
     */
    public static Map<String, String> getJsonData(JSONObject ujson, String[] keys) {
        Map<String, String> validMap = new HashMap<String, String>();

        for (String key : keys) {
            if (ujson.containsKey(key)) {
                validMap.put(key, ujson.getString(key));
            } else {
                validMap.put(key, "");
            }
        }
        return validMap;
    }

    /**
     * 取字符串的值，按指定的类型type返回；
     */
    public static Object takeStringValue(String str, String type) {
        Object retObj = null;
        switch (type) { // 初始化值
            case "long":
                retObj = 0l;
                break;
            case "String":
                retObj = "";
                break;
            case "int":
                retObj = 0;
                break;
        }

        if (StringUtils.isNotEmpty(str) && (!str.equals("null")) && (!str.equals("undefined"))) {
            switch (type) { // 初始化值
                case "long":
                    retObj = Long.parseLong(str);
                    break;
                case "String":
                    retObj = str.trim();
                    break;
                case "int":
                    retObj = Integer.parseInt(str);
                    break;
            }
        }

        return retObj;
    }

    /**
     * 取的json中的name的值，返回指定的type类型的值
     */
    public static Object takeJSONObjValue(JSONObject Obj, String name, String type) {
        Object retObj = null;
        switch (type) { // 初始化值
            case "long":
                retObj = 0l;
                break;
            case "String":
                retObj = "";
                break;
            case "int":
                retObj = 0;
                break;
            case "JSONObject":
            case "JSONArray":
                retObj = null;
                break;
        }

        if (Obj != null && Obj.containsKey(name) && (!Obj.getString(name).equals("null")) && (!Obj.getString(name).equals(""))
                && (!Obj.getString(name).equals("undefined"))) { // 若不为空，则取值
            switch (type) {
                case "long":
                    retObj = Obj.getLong(name);
                    break;
                case "String":
                    retObj = Obj.getString(name);
                    break;
                case "int":
                    retObj = Obj.getInt(name);
                    break;
                case "JSONObject":
                    retObj = Obj.getJSONObject(name);
                    break;
                case "JSONArray":
                    retObj = Obj.getJSONArray(name);
                    break;
            }

        }
        return retObj;
    }

    /**
     *
     * @Description: 获取json数据，取所有的keys值，返回map对象。
     * @author Trinity
     * @date 2016年8月12日 下午8:01:37
     * @version V1.0
     */
    public static String getRequestValue(HttpServletRequest request, String jsonData, String key) {
        // Map<String, Object> paramMap = new HashMap<String, Object>();
        JSONObject ujson = new JSONObject();
        String contentType = request.getContentType();
        String value = WebUtils.getCleanParam(request, key);
        if (value != null)
            return value;

        if (StringUtils.isEmpty(jsonData))
            return null;
        String jsonStr = jsonData;
        try {
            switch (contentType) {
                case "application/x-www-form-urlencoded":
                    jsonData = jsonData.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                    jsonStr = Tools.decoderStr(jsonData);
                    break;
                case "application/x-www-form-urlencoded; charset=UTF-8":
                    jsonData = jsonData.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                    jsonStr = Tools.decoderStr(jsonData);
                    break;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("传递的参数json串：" + jsonStr);

        try {
            ujson = JSONObject.fromObject(jsonStr);
        } catch (Exception e) {
            return "-1";
        }
        if (ujson.containsKey(key)) {
            value = ujson.getString(key);
        }
        if (StringUtils.isNotEmpty(value) && value.startsWith("{") && value.endsWith("}")) {
            ujson = JSONObject.fromObject(value);
            if (ujson.containsKey("id"))
                value = ujson.getString("id");
        }
        return value;
    }

    /**
     * 文件重命名
     */
    public static String renameFileName(String fileName) {
        String formatDate = new SimpleDateFormat("yyMMddHHmmss").format(new Date()); // 当前时间字符串
        int random = new Random().nextInt(10000);
        String extension = fileName.substring(fileName.lastIndexOf(".")); // 文件后缀

        return formatDate + random + extension;
    }
    
    public static String paddedDigit(int i, int legth) {
         //得到一个NumberFormat的实例
         NumberFormat nf = NumberFormat.getInstance();
         //设置是否使用分组
         nf.setGroupingUsed(false);
         //设置最大整数位数
         nf.setMaximumIntegerDigits(legth);
         //设置最小整数位数    
         nf.setMinimumIntegerDigits(legth);
         //返回补齐位数的字符串
         return nf.format(i);

    }
    
    /**
     * map转为javabean
     * @param map
     * @param beanClass
     * @return
     * @throws Exception
     */
	public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
		if (map == null)
			return null;

		Object obj = beanClass.newInstance();

		org.apache.commons.beanutils.BeanUtils.populate(obj, map);

		return obj;
	}

	/**
	 * javabean转为map
	 * @param obj
	 * @return
	 */
	public static Map<?, ?> objectToMap(Object obj) {
		if (obj == null)
			return null;

		return new org.apache.commons.beanutils.BeanMap(obj);
	}
    
   
		
    
}
